package org.clockworkmages.games.anno1186;

import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;

import org.clockworkmages.games.anno1186.dao.GameFilesList;
import org.clockworkmages.games.anno1186.dao.GameObjectsList;
import org.clockworkmages.games.anno1186.dao.SerializationUtil;
import org.clockworkmages.games.anno1186.gui.GameUiUtil;

public class GameDataService {

	private GameData gameData = new GameData();

	private Map<String, ImageIcon> imageIcons = new HashMap<String, ImageIcon>();

	public Map<String, ImageIcon> getImageIcons() {
		return imageIcons;
	}

	public void mergeGameDataFromResourceList(String gameFilesFilePath) {
		try {

			InputStream is = this.getClass().getClassLoader()
					.getResourceAsStream(gameFilesFilePath);

			InputStreamReader reader = new InputStreamReader(is);
			GameFilesList gameObjectsList = SerializationUtil.deserialize(
					reader, GameFilesList.class);
			for (String gameObjectsResource : gameObjectsList.getFiles()) {
				mergeGameDataFromResource(gameObjectsResource);
			}

		} catch (Exception e) {
			GameUiUtil.logError(e);
			throw new RuntimeException(e);
		}
	}

	public void mergeGameDataFromResource(String gameDataResourcePath) {
		try {
			InputStream is = this.getClass().getClassLoader()
					.getResourceAsStream(gameDataResourcePath);

			InputStreamReader reader = new InputStreamReader(is);
			GameObjectsList gameObjectsListFromFile = SerializationUtil
					.deserializeGameData(reader);
			gameData.merge(gameObjectsListFromFile);
		} catch (Exception e) {
			GameUiUtil.logError(e);
			throw new RuntimeException(e);
		}
	}

	public void mergeGameDataFromLocalDirectory(String gameDataDirectoryPath) {

		try {

			File gameDataDirectory = new File(gameDataDirectoryPath);
			if (!gameDataDirectory.exists() || !gameDataDirectory.isDirectory()) {
				return;
			}

			File[] gameObjectsListXmlFiles = gameDataDirectory.listFiles();
			for (File gameObjectListXmlFile : gameObjectsListXmlFiles) {
				GameUiUtil.logError("Loading game data file: "
						+ gameObjectListXmlFile.getAbsolutePath());
				Reader reader = new FileReader(gameObjectListXmlFile);

				GameObjectsList gameObjectsListFromFile = SerializationUtil
						.deserializeGameData(reader);
				gameData.merge(gameObjectsListFromFile);
			}
		} catch (Exception e) {
			GameUiUtil.logError(e);
			throw new RuntimeException(e);
		}
	}

	public GameData getGameData() {
		return gameData;
	}

	public void cleanGameData() {
		gameData = new GameData();
	}

}
